<?php

namespace App\Rules;

use App\Models\Application;
use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Arr;

class UrlSignature implements ValidationRule, DataAwareRule
{
    protected array $data = [];

    public function setData(array $data): static
    {
        $this->data = $data;

        return $this;
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $data = Arr::except($this->data, 'signature');
        ksort($data);
        $application = Application::where('app_key', $data['app_key'])->first();

        $params = array_merge($data, [
            'app_secret' => $application->app_secret,
        ]);
        if (strtoupper(md5(http_build_query($params))) != $value) {
            $fail(strtoupper(md5(http_build_query($params))));
            $fail('URL签名错误，请重试或联系 系统管理员');
        }
    }
}
